import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class AlipayService {
  private readonly logger = new Logger(AlipayService.name);

  constructor() {
    // 初始化支付宝支付配置
    // 实际实现需要支付宝商户账号等信息
  }

  /**
   * 创建支付宝订单
   * @param amount 金额
   * @param description 商品描述
   * @returns 支付参数
   */
  async createOrder(amount: number, description: string): Promise<any> {
    this.logger.log(`Creating Alipay order for amount: ${amount}`);

    try {
      // 实际实现需要调用支付宝下单接口
      // 这里返回模拟数据
      const order = {
        appId: process.env.ALIPAY_APP_ID,
        method: 'alipay.trade.app.pay',
        charset: 'utf-8',
        signType: 'RSA2',
        timestamp: new Date().toISOString(),
        version: '1.0',
        outTradeNo: this.generateOutTradeNo(),
        totalAmount: amount.toFixed(2),
        subject: description,
        // 实际还需要签名等参数
      };

      return order;
    } catch (error) {
      this.logger.error('Failed to create Alipay order', error);
      throw new Error('Failed to create Alipay order');
    }
  }

  /**
   * 查询订单状态
   * @param orderId 商户订单号
   * @returns 订单状态
   */
  async queryOrder(orderId: string): Promise<any> {
    this.logger.log(`Querying Alipay order: ${orderId}`);

    try {
      // 实际实现需要调用支付宝查询订单接口
      // 这里返回模拟数据
      return {
        status: 'TRADE_SUCCESS', // TRADE_SUCCESS/TRADE_FINISHED/WAIT_BUYER_PAY/TRADE_CLOSED
      };
    } catch (error) {
      this.logger.error(`Failed to query Alipay order: ${orderId}`, error);
      throw new Error('Failed to query Alipay order');
    }
  }

  /**
   * 生成商户订单号
   * @returns 订单号
   */
  private generateOutTradeNo(): string {
    return 'ALIPAY' + Date.now() + Math.random().toString(36).substring(2, 10).toUpperCase();
  }
}